/*
 * capture file client
 * Copyright (c) 2002 Fabrice Bellard
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Publi
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/* needed by inet_aton() */
#define _SVID_SOURCE
#define NULL_IF_CONFIG_SMALL(x) x

#include "libavutil/base64.h"
#include "libavutil/avstring.h"
#include "libavutil/intreadwrite.h"
#include "avformat.h"

#include <sys/time.h>
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <strings.h>
#include "network.h"
#include "rtsp.h"

#include "rtpdec.h"
#include "rdt.h"
#include "rtp_asf.h"
#include "rtp_vorbis.h"
#include "common.h"
#include "h263data.h"

#define SPACE_CHARS " \t\r\n"
/* we use memchr() instead of strchr() here because strchr() will return
 * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
#define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
static void skip_spaces(const char **pp)
{
    const char *p;
    p = *pp;
    while (redir_isspace(*p))
        p++;
    *pp = p;
}

static void get_word_until_chars(char *buf, int buf_size,
                                 const char *sep, const char **pp)
{
    const char *p;
    char *q;

    p = *pp;
    skip_spaces(&p);
    q = buf;
    while (!strchr(sep, *p) && *p != '\0') {
        if ((q - buf) < buf_size - 1)
            *q++ = *p;
        p++;
    }
    if (buf_size > 0)
        *q = '\0';
    *pp = p;
}

static void get_word_sep(char *buf, int buf_size, const char *sep,
                         const char **pp)
{
    if (**pp == '/') (*pp)++;
    get_word_until_chars(buf, buf_size, sep, pp);
}

static void get_word(char *buf, int buf_size, const char **pp)
{
    get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
}

/* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
   params>] */
static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p)
{
    char buf[256];
    int i;
    AVCodec *c;
    const char *c_name;

    /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
       see if we can handle this kind of payload */
    get_word_sep(buf, sizeof(buf), "/", &p);
    if (payload_type >= RTP_PT_PRIVATE) {
        RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
        while(handler) {
            if (!strcasecmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
                codec->codec_id = handler->codec_id;
                rtsp_st->dynamic_handler= handler;
                if(handler->open) {
                    rtsp_st->dynamic_protocol_context= handler->open();
                }
                break;
            }
            handler= handler->next;
        }
    } else {
        /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */
        /* search into AVRtpPayloadTypes[] */
        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
    }

    c = avcodec_find_decoder(codec->codec_id);
    if (c && c->name)
        c_name = c->name;
    else
        c_name = (char *)NULL;

    if (c_name) {
        get_word_sep(buf, sizeof(buf), "/", &p);
        i = atoi(buf);
        switch (codec->codec_type) {
            case CODEC_TYPE_AUDIO:
                av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name);
                codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
                codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
                if (i > 0) {
                    codec->sample_rate = i;
                    get_word_sep(buf, sizeof(buf), "/", &p);
                    i = atoi(buf);
                    if (i > 0)
                        codec->channels = i;
                    // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the
                    //  frequency.  No problem, but the sample rate is being set here by the sdp line.  Upcoming patch forthcoming. (rdm)
                }
                av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate);
                av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels);
                break;
            case CODEC_TYPE_VIDEO:
                av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name);
                break;
            default:
                break;
        }
        return 0;
    }

    return -1;
}

/* return the length and optionnaly the data */
static int hex_to_data(uint8_t *data, const char *p)
{
    int c, len, v;

    len = 0;
    v = 1;
    for(;;) {
        skip_spaces(&p);
        if (*p == '\0')
            break;
        c = toupper((unsigned char)*p++);
        if (c >= '0' && c <= '9')
            c = c - '0';
        else if (c >= 'A' && c <= 'F')
            c = c - 'A' + 10;
        else
            break;
        v = (v << 4) | c;
        if (v & 0x100) {
            if (data)
                data[len] = v;
            len++;
            v = 1;
        }
    }
    return len;
}

static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
                                  char *attr, char *value)
{
    switch (codec->codec_id) {
        case CODEC_ID_MPEG4:
        case CODEC_ID_AAC:
            if (!strcmp(attr, "config")) {
                /* decode the hexa encoded parameter */
                int len = hex_to_data(NULL, value);
                if (codec->extradata)
                    av_free(codec->extradata);
                codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
                if (!codec->extradata)
                    return;
                codec->extradata_size = len;
                hex_to_data(codec->extradata, value);
            }
            break;
        case CODEC_ID_VORBIS:
            ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
            break;
		case CODEC_ID_H263:
			if (!strcmp(attr, "QCIF")){
				int index = atoi(value);
				codec->width = h263_format[index][0];
				codec->height = h263_format[index][1];
			}
			break;
        default:
            break;
    }
    return;
}

typedef struct {
    const char *str;
    uint16_t type;
    uint32_t offset;
} AttrNameMap;

/* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
#define ATTR_NAME_TYPE_INT 0
#define ATTR_NAME_TYPE_STR 1
static const AttrNameMap attr_names[]=
{
    {"SizeLength",       ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, sizelength)},
    {"IndexLength",      ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexlength)},
    {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, indexdeltalength)},
    {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, profile_level_id)},
    {"StreamType",       ATTR_NAME_TYPE_INT, offsetof(RTPPayloadData, streamtype)},
    {"mode",             ATTR_NAME_TYPE_STR, offsetof(RTPPayloadData, mode)},
    {NULL, -1, -1},
};

/** parse the attribute line from the fmtp a line of an sdp resonse.  This is broken out as a function
* because it is used in rtp_h264.c, which is forthcoming.
*/
int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
{
    skip_spaces(p);
    if(**p) {
        get_word_sep(attr, attr_size, "=", p);
        if (**p == '=')
            (*p)++;
        get_word_sep(value, value_size, ";", p);
        if (**p == ';')
            (*p)++;
        return 1;
    }
    return 0;
}

/* parse a SDP line and save stream attributes */
static void sdp_parse_fmtp(AVStream *st, const char *p)
{
    char attr[256];
    /* Vorbis setup headers can be up to 12KB and are sent base64
     * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
    char value[16384];
    int i;

    RTSPStream *rtsp_st = st->priv_data;
    AVCodecContext *codec = st->codec;
    RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;

    /* loop on each attribute */
    while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
    {
        /* grab the codec extra_data from the config parameter of the fmtp line */
        sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
                              attr, value);
        /* Looking for a known attribute */
        for (i = 0; attr_names[i].str; ++i) {
            if (!strcasecmp(attr, attr_names[i].str)) {
                if (attr_names[i].type == ATTR_NAME_TYPE_INT)
                    *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
                else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
                    *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
            }
        }
    }
}

/** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
 *  and end time.
 *  Used for seeking in the rtp stream.
 */
static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
{
    char buf[256];

    skip_spaces(&p);
    if (!av_stristart(p, "npt=", &p))
        return;

    *start = AV_NOPTS_VALUE;
    *end = AV_NOPTS_VALUE;

    get_word_sep(buf, sizeof(buf), "-", &p);
    *start = parse_date(buf, 1);
    if (*p == '-') {
        p++;
        get_word_sep(buf, sizeof(buf), "-", &p);
        *end = parse_date(buf, 1);
    }
//    av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
//    av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
}

typedef struct SDPParseState {
    /* SDP only */
    struct in_addr default_ip;
    int default_ttl;
    int skip_media; ///< set if an unknown m= line occurs
} SDPParseState;

static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
                           int letter, const char *buf)
{
    RTSPState *rt = s->priv_data;
    char buf1[64], st_type[64];
    const char *p;
    enum CodecType codec_type;
    int payload_type, i;
    AVStream *st;
    RTSPStream *rtsp_st;
    struct in_addr sdp_ip;
    int ttl;

    dprintf(s, "sdp: %c='%s'\n", letter, buf);

    p = buf;
    if (s1->skip_media && letter != 'm')
        return;
    switch(letter) {
    case 'c':
        get_word(buf1, sizeof(buf1), &p);
        if (strcmp(buf1, "IN") != 0)
            return;
        get_word(buf1, sizeof(buf1), &p);
        if (strcmp(buf1, "IP4") != 0)
            return;
        get_word_sep(buf1, sizeof(buf1), "/", &p);
        if (inet_aton(buf1, &sdp_ip) == 0)
            return;
        ttl = 16;
        if (*p == '/') {
            p++;
            get_word_sep(buf1, sizeof(buf1), "/", &p);
            ttl = atoi(buf1);
        }
        if (s->nb_streams == 0) {
            s1->default_ip = sdp_ip;
            s1->default_ttl = ttl;
        } else {
            st = s->streams[s->nb_streams - 1];
            rtsp_st = st->priv_data;
            rtsp_st->sdp_ip = sdp_ip;
            rtsp_st->sdp_ttl = ttl;
        }
        break;
    case 's':
        av_metadata_set(&s->metadata, "title", p);
        break;
    case 'i':
        if (s->nb_streams == 0) {
            av_metadata_set(&s->metadata, "comment", p);
            break;
        }
        break;
    case 'm':
        /* new stream */
        s1->skip_media = 0;
        get_word(st_type, sizeof(st_type), &p);
        if (!strcmp(st_type, "audio")) {
            codec_type = CODEC_TYPE_AUDIO;
        } else if (!strcmp(st_type, "video")) {
            codec_type = CODEC_TYPE_VIDEO;
        } else if (!strcmp(st_type, "application")) {
            codec_type = CODEC_TYPE_DATA;
        } else {
            s1->skip_media = 1;
            return;
        }
        rtsp_st = av_mallocz(sizeof(RTSPStream));
        if (!rtsp_st)
            return;
        rtsp_st->stream_index = -1;
        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);

        rtsp_st->sdp_ip = s1->default_ip;
        rtsp_st->sdp_ttl = s1->default_ttl;

        get_word(buf1, sizeof(buf1), &p); /* port */
        rtsp_st->sdp_port = atoi(buf1);

        get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */

        /* XXX: handle list of formats */
        get_word(buf1, sizeof(buf1), &p); /* format list */
        rtsp_st->sdp_payload_type = atoi(buf1);

        if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
            /* no corresponding stream */
        } else {
            st = av_new_stream(s, 0);
            if (!st)
                return;
            st->priv_data = rtsp_st;
            rtsp_st->stream_index = st->index;
            st->codec->codec_type = codec_type;
            if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
                /* if standard payload type, we can find the codec right now */
                ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
            }
        }
        /* put a default control url */
        av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
        break;
    case 'a':
        if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
            char proto[32];
            /* get the control url */
            st = s->streams[s->nb_streams - 1];
            rtsp_st = st->priv_data;

            /* XXX: may need to add full url resolution */
            url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
            if (proto[0] == '\0') {
                /* relative control URL */
                av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
                av_strlcat(rtsp_st->control_url, p,   sizeof(rtsp_st->control_url));
            } else {
                av_strlcpy(rtsp_st->control_url, p,   sizeof(rtsp_st->control_url));
            }
        } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
            /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
            get_word(buf1, sizeof(buf1), &p);
            payload_type = atoi(buf1);
            st = s->streams[s->nb_streams - 1];
            rtsp_st = st->priv_data;
            sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
        } else if (av_strstart(p, "fmtp:", &p)) {
            /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
            get_word(buf1, sizeof(buf1), &p);
            payload_type = atoi(buf1);
            for(i = 0; i < s->nb_streams;i++) {
                st = s->streams[i];
                rtsp_st = st->priv_data;
                if (rtsp_st->sdp_payload_type == payload_type) {
                    if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
                        if(!rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf)) {
                            sdp_parse_fmtp(st, p);
                        }
                    } else {
                        sdp_parse_fmtp(st, p);
                    }
                }
            }
        } else if(av_strstart(p, "framesize:", &p)) {
            // let dynamic protocol handlers have a stab at the line.
            get_word(buf1, sizeof(buf1), &p);
            payload_type = atoi(buf1);
            for(i = 0; i < s->nb_streams;i++) {
                st = s->streams[i];
                rtsp_st = st->priv_data;
                if (rtsp_st->sdp_payload_type == payload_type) {
                    if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
                        rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf);
                    } else {
						get_word(buf1, sizeof(buf1), &p);
						st->codec->width = atoi(buf1);
						st->codec->height = atoi(strstr(buf1, "-") + 1);
						st->codec->frame_size = st->codec->width * st->codec->height;
					}
                }
            }
        } else if(av_strstart(p, "range:", &p)) {
            int64_t start, end;

            // this is so that seeking on a streamed file can work.
            rtsp_parse_range_npt(p, &start, &end);
            s->start_time= start;
            s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
        } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
            if (atoi(p) == 1)
                rt->transport = RTSP_TRANSPORT_RDT;
        } else {
            if (rt->server_type == RTSP_SERVER_WMS)
                ff_wms_parse_sdp_a_line(s, p);
            if (s->nb_streams > 0) {
                if (rt->server_type == RTSP_SERVER_REAL)
                    ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);

                rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
                if (rtsp_st->dynamic_handler &&
                    rtsp_st->dynamic_handler->parse_sdp_a_line)
                    rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1,
                        rtsp_st->dynamic_protocol_context, buf);
            }
        }
        break;
    }
}

static int sdp_parse(AVFormatContext *s, const char *content)
{
    const char *p;
    int letter;
    /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
     * contain long SDP lines containing complete ASF Headers (several
     * kB) or arrays of MDPR (RM stream descriptor) headers plus
     * "rulebooks" describing their properties. Therefore, the SDP line
     * buffer is large.
     *
     * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
    char buf[16384], *q;
    SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;

    memset(s1, 0, sizeof(SDPParseState));
    p = content;
    for(;;) {
        skip_spaces(&p);
        letter = *p;
        if (letter == '\0')
            break;
        p++;
        if (*p != '=')
            goto next_line;
        p++;
        /* get the content */
        q = buf;
        while (*p != '\n' && *p != '\r' && *p != '\0') {
            if ((q - buf) < sizeof(buf) - 1)
                *q++ = *p;
            p++;
        }
        *q = '\0';
        sdp_parse_line(s, s1, letter, buf);
    next_line:
        while (*p != '\n' && *p != '\0')
            p++;
        if (*p == '\n')
            p++;
    }
    return 0;
}

static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
{
    const char *p;
    int v;

    p = *pp;
    skip_spaces(&p);
    v = strtol(p, (char **)&p, 10);
    if (*p == '-') {
        p++;
        *min_ptr = v;
        v = strtol(p, (char **)&p, 10);
        *max_ptr = v;
    } else {
        *min_ptr = v;
        *max_ptr = v;
    }
    *pp = p;
}

/* XXX: only one transport specification is parsed */
static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
{
    char transport_protocol[16];
    char profile[16];
    char lower_transport[16];
    char parameter[16];
    RTSPTransportField *th;
    char buf[256];

    reply->nb_transports = 0;

    for(;;) {
        skip_spaces(&p);
        if (*p == '\0')
            break;

        th = &reply->transports[reply->nb_transports];

        get_word_sep(transport_protocol, sizeof(transport_protocol),
                     "/", &p);
        if (!strcasecmp (transport_protocol, "rtp")) {
            get_word_sep(profile, sizeof(profile), "/;,", &p);
            lower_transport[0] = '\0';
            /* rtp/avp/<protocol> */
            if (*p == '/') {
                get_word_sep(lower_transport, sizeof(lower_transport),
                             ";,", &p);
            }
            th->transport = RTSP_TRANSPORT_RTP;
        } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
                   !strcasecmp (transport_protocol, "x-real-rdt")) {
            /* x-pn-tng/<protocol> */
            get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
            profile[0] = '\0';
            th->transport = RTSP_TRANSPORT_RDT;
        }
        if (!strcasecmp(lower_transport, "TCP"))
            th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
        else
            th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;

        if (*p == ';')
            p++;
        /* get each parameter */
        while (*p != '\0' && *p != ',') {
            get_word_sep(parameter, sizeof(parameter), "=;,", &p);
            if (!strcmp(parameter, "port")) {
                if (*p == '=') {
                    p++;
                    rtsp_parse_range(&th->port_min, &th->port_max, &p);
                }
            } else if (!strcmp(parameter, "client_port")) {
                if (*p == '=') {
                    p++;
                    rtsp_parse_range(&th->client_port_min,
                                     &th->client_port_max, &p);
                }
            } else if (!strcmp(parameter, "server_port")) {
                if (*p == '=') {
                    p++;
                    rtsp_parse_range(&th->server_port_min,
                                     &th->server_port_max, &p);
                }
            } else if (!strcmp(parameter, "interleaved")) {
                if (*p == '=') {
                    p++;
                    rtsp_parse_range(&th->interleaved_min,
                                     &th->interleaved_max, &p);
                }
            } else if (!strcmp(parameter, "multicast")) {
                if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
                    th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
            } else if (!strcmp(parameter, "ttl")) {
                if (*p == '=') {
                    p++;
                    th->ttl = strtol(p, (char **)&p, 10);
                }
            } else if (!strcmp(parameter, "destination")) {
                struct in_addr ipaddr;

                if (*p == '=') {
                    p++;
                    get_word_sep(buf, sizeof(buf), ";,", &p);
                    if (inet_aton(buf, &ipaddr))
                        th->destination = ntohl(ipaddr.s_addr);
                }
            }
            while (*p != ';' && *p != '\0' && *p != ',')
                p++;
            if (*p == ';')
                p++;
        }
        if (*p == ',')
            p++;

        reply->nb_transports++;
    }
}

static int
rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
{
    RTSPState *rt = s->priv_data;
    AVStream *st = NULL;

    /* open the RTP context */
    if (rtsp_st->stream_index >= 0)
        st = s->streams[rtsp_st->stream_index];
    if (!st)
        s->ctx_flags |= AVFMTCTX_NOHEADER;

    if (rt->transport == RTSP_TRANSPORT_RDT)
        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
                                            rtsp_st->dynamic_protocol_context,
                                            rtsp_st->dynamic_handler);
    else
        rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
                                         rtsp_st->sdp_payload_type,
                                         &rtsp_st->rtp_payload_data);

    if (!rtsp_st->transport_priv) {
         return AVERROR(ENOMEM);
    } else if (rt->transport != RTSP_TRANSPORT_RDT) {
        if(rtsp_st->dynamic_handler) {
            rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
                                           rtsp_st->dynamic_protocol_context,
                                           rtsp_st->dynamic_handler);
        }
    }

    return 0;
}

#define SDP_MAX_SIZE 8192
#define CONTINUE 100
#define MAX_PORT 10
#define TCP_IP 0x0
#define TCP 0x06
#define UDP 0x11
#define SKIP_CAP_HEADER url_fskip(s->pb, 24)
short src_port_list[MAX_PORT] = {0};
int src_port_index = 0;
short dst_port_list[MAX_PORT] = {0};
int dst_port_index = 0;
int need_more = 0;
int pkt_count = 0;

char *strcasestr(const char *haystack, const char *needle);

static int get_tcp_udp_size(ByteIOContext *s, int type, int *port) {
	url_fskip(s, 8 + 4); //cap frame header
	int checksum = get_le32(s);
	if (url_feof(s)) {
		return -1;
	}
	url_fskip(s, 14); //ethernet header

	url_fskip(s, 2); //IP header 1
	int pkt_size = get_be16(s);
	checksum -= pkt_size + 14;
	url_fskip(s, 5); //IP header 1
	unsigned char proto = get_byte(s);
	url_fskip(s, 10); //IP header 2
	av_log(NULL, AV_LOG_DEBUG, "Packet index = %d, IP length = %d\n", ++pkt_count, pkt_size);
	pkt_size -= 20;

	if (type != TCP_IP && type != proto) {
		url_fskip(s, pkt_size + checksum); //whole package
		return 0;
	}

	int src_port = get_be16(s);
	if (port != NULL) *port = src_port;
	int dst_port = get_be16(s);
	pkt_size -= 4;
    
	for (int i = 0; i < src_port_index; i++) {
		if (src_port_list[i] == src_port) {
			goto handle;
		}
	}
	
	for (int i = 0; i < dst_port_index; i++) {
		if (dst_port_list[i] == dst_port) {
			goto handle;
		}
	}
	
	url_fskip(s, pkt_size + checksum); //whole package
	return 0;

handle:
	switch (proto) {
		case TCP: 
			url_fskip(s, 8); //skip TCP header
			pkt_size -= 8;

			int tcp_h_len = get_byte(s) >> 4 & 0xf;
			tcp_h_len = (tcp_h_len - 3) * 4 - 1;
			pkt_size--;

			url_fskip(s, tcp_h_len); 
			pkt_size -= tcp_h_len;

			return pkt_size + checksum;
		case UDP: 
			url_fskip(s, 4); //skip UDP header
			pkt_size -= 4;
			return pkt_size + checksum;
		default:
			url_fskip(s, pkt_size + checksum); //skip UDP header
	}

	return 0;
}

typedef int (*pkt_handler)(ByteIOContext *s, unsigned char *buf, int size);

static int handle_pkt(ByteIOContext *s, unsigned char *buf, pkt_handler handler, 
		int type, int *pkt_size, int *src_port) {
	int ret = 0;
	int size = 0;

	do {	
		size = get_tcp_udp_size(s, type, src_port);
		if (size < 0) {
			return -1;
		} else if (!size) {
			ret = CONTINUE;
			continue;
		}

		ret = handler(s, buf, size); 
	}while (ret == CONTINUE);

	if (pkt_size != NULL) *pkt_size = size;
	return ret;
}

static int handle_pkt_t(ByteIOContext *s, unsigned char *buf, pkt_handler handler) {
	return handle_pkt(s, buf, handler, TCP, NULL, NULL); 
}

int get_sdp_content(ByteIOContext *s, unsigned char *buf, int pkt_size) {
	static int sdp_len = 0;
	static int sdp_pos = 0;

	if (sdp_pos != 0) {
		get_buffer(s, buf + sdp_pos, pkt_size);
		sdp_pos += pkt_size;
	} else {
		get_buffer(s, buf, pkt_size);

		unsigned char *pos = strcasestr(buf, "application/sdp");
		if (pos == NULL) return CONTINUE;

		pos = strcasestr(buf, "Content-length:");
		if (pos == NULL) return -1;

		char *end;
		while (*pos != '\n' && (*pos < 30 || *pos > 39)) pos++;

		if (*pos == '\n') return -1;

		sdp_len = strtol(pos, &end, 0);

		pos = strstr(buf, "\r\n\r\n");
		if (pos != NULL) {
			pos += 4;
		}
		else {
			pos = strstr(buf, "\n\n");
			if (pos != NULL) {
				pos += 2;
			}
		}
		if (pos == NULL) return -1;

		int hd_len = pos - buf;
		memmove(buf, buf + hd_len, pkt_size - hd_len);
		sdp_pos = pkt_size - hd_len;
	}

	if (sdp_len == sdp_pos) {
		buf[sdp_pos] = '\0';
		return 0;
	} else {
		return CONTINUE;
	}
}

static void add_port(short port) {
	int i = 0;
	for (; i < src_port_index; i++) {
		if (port == src_port_list[i]) return;
	}

	src_port_list[src_port_index++] = port;
}

int reg_trans_port(ByteIOContext *s, unsigned char *buf, int pkt_size) {
	get_buffer(s, buf, pkt_size);

	unsigned char *pos = strcasestr(buf, "server_port=");
	if (pos == NULL) return CONTINUE;
	pos += strlen("server_port=");

	char *end;
	long int rtp_port = strtol(pos, &end, 0);
	long int rtcp_port = 0;
	if (*end == '-') {
		end++;
		rtcp_port = strtol(end, &end, 0);

		add_port(rtp_port);
		//add_port(rtcp_port);
		av_log(NULL, AV_LOG_DEBUG, "Add transport port %ld, %ld\n", rtp_port, rtcp_port);
	}

	return 0;
}

//static int get_sdp_content(ByteIOContext *s, unsigned char *buf, int size) {
//	int sdp_size = 0;
//	int buf_pos = 0;
//
//	int pkt_size;
//	
//	do {	
//		pkt_size = get_tcp_udp_size(s, TCP);
//		get_buffer(s, buf + buf_pos, pkt_size);
//
//		if (sdp_size == 0) {
//			int ready_size = get_sdp_size(buf, pkt_size, &sdp_size);
//			if (ready_size <= 0) continue;
//
//			memmove(buf, buf + (pkt_size - ready_size), ready_size);
//			buf_pos = ready_size;
//		}	
//	}while (buf_pos >= sdp_size);
//
//}

static int cap_read_header(AVFormatContext *s,
                           AVFormatParameters *ap)
{
    RTSPState *rt = s->priv_data;
    RTSPStream *rtsp_st;
    int ret, i;
    char *content;

    /* read the whole sdp file */
    content = av_malloc(SDP_MAX_SIZE);
	add_port(554);
	SKIP_CAP_HEADER;
	ret = handle_pkt_t(s->pb, content, get_sdp_content);
    if (ret < 0) {
        return AVERROR_INVALIDDATA;
    }

    sdp_parse(s, content);

    /* open each RTP stream */
    for(i=0;i<rt->nb_rtsp_streams;i++) {
        rtsp_st = rt->rtsp_streams[i];
        if ((ret = rtsp_open_transport_ctx(s, rtsp_st)))
			break;

		ret = handle_pkt_t(s->pb, content, reg_trans_port);
		if (ret < 0) {
			break;
		}
    }

    av_free(content);
    return ret;
}

static int cap_read_packet(AVFormatContext *s,
                            AVPacket *pkt)
{
    RTSPState *rt = s->priv_data;
    int ret, len, src_port;
    uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];

    /* get next frames from the same RTP packet */
    if (rt->cur_transport_priv) {
		ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
        if (ret == 0) {
            rt->cur_transport_priv = NULL;
            return 0;
        } else if (ret == 1) {
            return 0;
        } else {
            rt->cur_transport_priv = NULL;
        }
    }

	ret = handle_pkt(s->pb, buf, get_buffer, UDP, &len, &src_port);
    if (ret < 0) {
        return AVERROR_EOF;
    }

    RTSPStream *rtsp_st = rt->rtsp_streams[src_port == 12940 ? 1 : 0];
    if (len < 0)
        return len;
    if (len == 0)
        return AVERROR_EOF;
	ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
    if (ret < 0)
        return -1;
    if (ret == 1) {
        /* more packets may follow, so we save the RTP context */
        rt->cur_transport_priv = rtsp_st->transport_priv;
    }

    return 0;
}

#if CONFIG_CAP_DEMUXER
AVInputFormat cap_demuxer = {
    "cap",
    NULL_IF_CONFIG_SMALL("CAP"),
    sizeof(RTSPState),
    NULL,
    cap_read_header,
    cap_read_packet,
	.extensions = "cap",
};
#endif

